package com.formiaomiao.demain.service.impl;

import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.dao.FriendRemarksDao;
import com.formiaomiao.demain.dao.UserDao;
import com.formiaomiao.demain.model.EasemobUserBean;
import com.formiaomiao.demain.model.FriendRemarksBean;
import com.formiaomiao.demain.model.Result;
import com.formiaomiao.demain.model.UserBean;
import com.formiaomiao.demain.service.UserService;
import com.formiaomiao.demain.utils.HttpClientUtils;
import com.formiaomiao.demain.utils.ResultUtil;
import com.google.gson.Gson;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;//这里会报错，但是并不会影响
    @Autowired
    private FriendRemarksDao friendRemarksDao;

    @Transactional(value = "demain")
    @Override
    public Result<String> registerUser(UserBean userBean) {
        if (userDao.Checkrepetition(userBean.getUserPhone()) != null) {
            return ResultUtil.error(20, "账号已存在");
        }
        if (userBean.getValidateCode().equals("验证码错误")) {
            return ResultUtil.error(401, "短信发送失败");
        } else {
            userBean.setNeteaseUid(registerRingId(userBean.getUserName(), userBean.getPassWord()));
            int result = userDao.registerUser(userBean);
            String str = "";
            if (result == 1) {
                str = "success";

            } else {
                str = "error";
            }
            return ResultUtil.success(str);
        }
    }

    @Override
    public Result<UserBean> SignInUser(UserBean userBean) {
        UserBean userBeanDomains = userDao.SignInUser(userBean);
        if (userBeanDomains == null) {
            return ResultUtil.error(30, "账号或密码错误");
        }
        // Create Twt token
        String jwtToken = Jwts.builder().setSubject(userBean.getUserName()).claim("roles", "member").setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "secretkey").compact();
        userBeanDomains.setToken(jwtToken);
        userBeanDomains.setPassWord(null);
        return ResultUtil.success(userBeanDomains);
    }

    @Transactional(value = "demain")
    @Override
    public Result<String> UpdateHead(UserBean userBean) {
        if (userDao.UpdateHead(userBean) == 0) {
            return ResultUtil.error(400, "头像上传失败");
        } else {
            return ResultUtil.success("头像上传成功");
        }
    }

    @Transactional(value = "demain")
    @Override
    public Result<String> UpdatePwd(UserBean userBean) {
        if (userDao.UpdatePwd(userBean) == 0) {
            return ResultUtil.error(50, "密码修改失败");
        } else {
            return ResultUtil.success("密码修改成功");
        }
    }

    @Transactional(value = "demain")
    @Override
    public Result<String> UpdateNickName(UserBean userBean) {
        if (userDao.UpdateNickName(userBean) == 0) {
            return ResultUtil.error(400, "昵称修改失败");
        } else {
            if (updateRingNickname(userDao.selectUser(userBean.getId()).getUserName(),
                    userBean.getNickName()).equals("200")) {
                return ResultUtil.success("昵称修改成功");
            } else {
                return ResultUtil.error(400, "昵称修改失败");
            }
        }
    }

    @Override
    public Result<Boolean> sendSMSMessage(Boolean b) {
        if (b) {
            return ResultUtil.success("短信发送成功");
        } else {
            return ResultUtil.error(60, "短信发送失败");
        }
    }

    @Transactional(value = "demain")
    @Override
    public Result<String> ForgetPwd(UserBean userBean) {
        if (userBean.getValidateCode().equals("验证码错误")) {
            return ResultUtil.error(401, "短信发送失败");
        } else {
            if (userDao.UpdateNickName(userBean) == 0) {
                return ResultUtil.error(50, "密码修改失败");
            } else {
                return ResultUtil.success("密码修改成功");
            }
        }
    }

    /**
     * 通过id获取用户详情
     *
     * @param userBean
     * @return
     */
    @Override
    public Result<UserBean> selectUser(UserBean userBean) {
        if (userDao.selectUser(userBean.getId()) == null) {
            return ResultUtil.error(400, "查询用户失败");
        } else {
            UserBean bean = userDao.selectUser(userBean.getId());
            return ResultUtil.success(bean);
        }
    }

    /**
     * 通过username获取用户详情
     *
     * @param userBean
     * @return
     */
    @Override
    public Result<UserBean> usernameselect(UserBean userBean) {
        if (userDao.usernameselect(userBean) == null) {
            return ResultUtil.error(400, "查询用户失败");
        } else {
            UserBean bean = userDao.usernameselect(userBean);
            return ResultUtil.success(bean);
        }
    }

    @Override
    public Result<UserBean> Listusernameselect(Integer userid, List<UserBean> userBean) {
        List<UserBean> beanList = new ArrayList<>();
        for (int i = 0; i < userBean.size(); i++) {
            UserBean bean = new UserBean();
            bean.setUserName(userBean.get(i).getUserName());
            FriendRemarksBean friendRemarksBean = new FriendRemarksBean();
            friendRemarksBean.setFriendfrom(userid);
            friendRemarksBean.setFriendto(userDao.usernameselect(bean).getId());
            beanList.add(userDao.Listusernameselect(userBean.get(i)));
            if (friendRemarksDao.SelectRemarks(friendRemarksBean) == null) {
                beanList.get(i).setFriendremarks("");
            } else {
                beanList.get(i).setFriendremarks(friendRemarksDao.SelectRemarks(friendRemarksBean)
                        .getFriendremarks() == null ? "" : friendRemarksDao.SelectRemarks(friendRemarksBean)
                        .getFriendremarks());
            }
        }
        return ResultUtil.success(beanList);
    }

    /**
     * 注册环信id
     *
     * @param username
     * @param password
     * @return
     */
    private String registerRingId(String username, String password) {
        Gson gson = new Gson();
        EasemobUserBean userBean = new EasemobUserBean();
        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        String json = HttpClientUtils.putJsonParams(BaseUrl.REGISTERACTION,
                "YWMtCQ8siOftEeiQWxfoSEhqyQAAAAAAAAAAAAAAAAAAAAEns8oA1a4R6I7D0d0-2pmYAgMAAAFnEXvXZQBPGgAyODuqYLjy0kNfQO_1B8mpFmel_98SSt6J_fO2dN9H9w"
                , HttpClientUtils.mapToJson(map));
        userBean = gson.fromJson(json, EasemobUserBean.class);
        return userBean.getEntities().get(0).getUuid();
    }

    /**
     * 修改环信昵称
     *
     * @param username
     * @param name
     * @return
     */
    private String updateRingNickname(String username, String name) {
        Gson gson = new Gson();
        Map<String, String> map = new HashMap<>();
        map.put("nickname", name);
        if (HttpClientUtils.putJsonParams(BaseUrl.REGISTERACTION + "/" + username,
                "YWMtCQ8siOftEeiQWxfoSEhqyQAAAAAAAAAAAAAAAAAAAAEns8oA1a4R6I7D0d0-2pmYAgMAAAFnEXvXZQBPGgAyODuqYLjy0kNfQO_1B8mpFmel_98SSt6J_fO2dN9H9w"
                , HttpClientUtils.mapToJson(map)).contains("200")) {
            return "200";
        } else {
            return "400";
        }
    }
}
